const userServices = require("../../services/admin/userService");
const JWT = require("../../utils/jwt");

let userController = {
  // 登陆
  login: async (req, res) => {
    const result = await userServices.login(req.body);
    if (result.length === 0) {
      res.status(500).send({
        code: 500,
        data: "无法查找到该用户",
      });
    } else {
      res.send({
        code: 200,
        data: JWT.generate({ ...req.body }, "30000s"),
      });
    }
  },
  // 获取用户信息
  getInfo: async (req, res) => {
    const token = req.headers.authorization.split(" ")[1];
    const { username, password } = JWT.verify(token);
    const result = await userServices.getInfo({ username, password });
    res.json({
      code: 200,
      data: {
        username: result.username,
        password: result.password,
        role: result.role,
        avater: result.avater,
        desc: result.desc,
      },
    });
  },
  // 新增用户
  addUser: async (req, res) => {
    const result = await userServices.addUser({
      ...req.body,
      avater: req.file ? req.file.path.replace("public", "") : null,
    });
    if (result) {
      res.send({
        code: 200,
        data: "添加成功",
      });
    } else {
      res.status(500).json({
        code: 500,
        data: "添加失败",
      });
    }
  },
  // 获取用户列表
  getUserList: async (req, res) => {
    const result = await userServices.getUserList();
    res.json({
      code: 200,
      data: result,
    });
  },
  // 删除用户
  deleteUser: async (req, res) => {
    const result = await userServices.deleteUser(req.params.id);
    if (result) {
      res.send({
        code: 200,
        data: "删除成功",
      });
    }
  },
  editUser: async (req, res) => {
    const result = await userServices.editUser({
      ...req.body,
      avater: req.file ? req.file.path.replace("public", "") : null,
    });
    if (result) {
      res.send({
        code: 200,
        data: "修改成功",
      });
    } else {
      res.status(500).json({
        code: 500,
        data: "添加失败",
      });
    }
  },
};

module.exports = userController;
